package com.zyk.leetcode;

import java.util.Arrays;

/**
 * @author zhangsan
 * @date 2021/4/4 18:37
 */
public class J21 {

    /** https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/ */
    public static int[] exchange(int[] nums) {
        int l = 0, r = nums.length-1;
        int[] ans = new int[nums.length];
        for (int num : nums) {
            if( (num&1) == 0) {
                ans[r--] = num;
            }else {
                ans[l++] = num;
            }
        }
        return ans;
    }
    // 快速换位
    public static int[] exchange2(int[] nums) {
        int l = 0, r = nums.length-1;
        while (l < r) {
            // 找到右边的偶数
            while (l < r && (nums[l] &1) == 1) {
                l++;
            }
            while (l < r && (nums[r] & 1) == 0) {
                r--;
            }
            // 找到了左边的奇数, 右边的偶数,然后换位置
            int temp = nums[l];
            nums[l] = nums[r];
            nums[r] = temp;
        }
        return nums;
    }


    // for test
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        int[] ans = exchange(arr);
        int[] ans2 = exchange2(arr);
        System.out.println(Arrays.toString(ans));
        System.out.println(Arrays.toString(ans2));
    }

}
